package com.xique.blelock.view.AcountManager;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.xique.blelock.Jpush.JpushUtil;
import com.xique.blelock.NetUtils.XqNetClient;
import com.xique.blelock.Utils.ACache;
import com.xique.blelock.Utils.MD5Util;
import com.xique.blelock.Utils.SettingManager;
import com.xique.blelock.Utils.Stringkey;
import com.xique.blelock.Utils.TimeUtil;
import com.xique.blelock.model.LockInfo;
import com.xique.blelock.model.UserInfo;
import com.xique.blelock.model.VCodeType;
import com.xique.blelock.view.BaseActivity;
import com.xique.blelock.view.Home_Activity;
import com.xique.blelock.R;
import com.xique.blelock.view.Thtreepackage.CountDownButtonHelper;

import org.json.JSONException;
import org.json.JSONObject;


import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class Login_Activity extends BaseActivity implements View.OnClickListener {
    private static String TAG="Login_Activity";
    private Button Loginjiemiqan;
    private TextView ZHUCEJIEMIAN,Forgerpassord;
    @BindView(R.id.phones)
    EditText phones;

    @BindView(R.id.passward)
    EditText   passwards;

    @BindView(R.id.getvcode)
    EditText authcode;

//    @BindView(R.id.getvcode)
//    TextView codeText;

    @BindView(R.id.yanzhnema)
    TextView sendCodeBtn;



    //切换登录模式
    @BindView(R.id.loginswitch)
     ToggleButton lgswitch;

    //密码输入框
    @BindView(R.id.passwdlayout)
     View passlayout;

    //验证码发送按钮
    @BindView(R.id.codelayout)
     View codelayout;

    @BindView(R.id.LOGINactivity)
    Button loginbtn;


    @BindView(R.id.passwdmode)
    ToggleButton passwdmode;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.loginactivity);
        ButterKnife.bind(this);
        initview();



    }

    /**
     * 初始化
     */
    private void initview() {
        Loginjiemiqan = findViewById(R.id.LOGINactivity);
        ZHUCEJIEMIAN = findViewById(R.id.zhucejimain);
        Forgerpassord = findViewById(R.id.forgetpassword);
        phones = findViewById(R.id.phones);
        passwards = findViewById(R.id.passward);
        Forgerpassord.setOnClickListener(this);
        ZHUCEJIEMIAN.setOnClickListener(this);
        Loginjiemiqan.setOnClickListener(this);




        phones.addTextChangedListener(textWatcher);
        passwards.addTextChangedListener(textWatcher);
        authcode.addTextChangedListener(textWatcher);
        loginbtn.setEnabled(false);


    }

    @OnClick({R.id.loginswitch})
    public void SwitchClick(){

        if(lgswitch.isChecked()){
            passlayout.setVisibility(View.GONE);
            codelayout.setVisibility(View.VISIBLE);

        }else{
            passlayout.setVisibility(View.VISIBLE);
            codelayout.setVisibility(View.GONE);
        }
    }

    //切换密码模式
    @OnClick(R.id.passwdmode)
    public void SwitchPwdmod() {
        if(passwdmode.isChecked()){
            //默认状态显示密码--设置文本 要一起写才能起作用 InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD
            passwards.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        }else{
            //选择状态 显示明文--设置为可见的密码
            passwards.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
        }
    }

    @OnClick(R.id.agreement)
    public void AgreeMent(){
        Intent serverIntent = new Intent(this, AgreementActivity.class); // 跳转登录界面
        startActivity(serverIntent);
    }

    @OnClick(R.id.yanzhnema)
    public void getAuthcode(){
        if(TextUtils.isEmpty(phones.getText())){
            showToast(this,"请输入手机号");
            return;
        }
        String phonenumber = phones.getText().toString();//获取电话号码
        Pattern p = Pattern.compile("[0-9]*");
        Matcher m = p.matcher(phonenumber);
        if (m.matches()) {
            if (phonenumber.length() >= 11) {
                XqNetClient netClient =  new XqNetClient();
                JSONObject body1 = new JSONObject();
                try {
                    body1.put("phone",phonenumber);
                    body1.put("mode", VCodeType.Login);
                    body1.put("timestamp",TimeUtil.getLastTime());
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                showProgressDialog();
                netClient.sendAuthCode(body1.toString()).enqueue(new Callback<String>() {//获取验证码
                    @Override
                    public void onResponse(Call<String> call, Response<String> response) {
                        //System.out.println("-===获取的验证码是："+ response.body());

                        if (response.body().contains("成功")) {
                            String getdate = response.body();
                            String codes = "0";
                            showToast(Login_Activity.this,"验证码已发送，请注意查收");
                            try {
                                JSONObject jsonObject = new JSONObject(getdate);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                        hideProgressDialog();
                    }

                    @Override
                    public void onFailure(Call<String> call, Throwable t) {
                        t.printStackTrace();
                        hideProgressDialog();

                    }
                });
                CountDownButtonHelper helper = new CountDownButtonHelper(sendCodeBtn,
                        "发送验证码", 60, 1);
                helper.setOnFinishListener(new CountDownButtonHelper.OnFinishListener() {

                    @Override
                    public void finish() {
                        sendCodeBtn.setText("重新发送");
                    }
                });
                helper.start();
            }else {
                Toast.makeText(this, "输入手机号有误", Toast.LENGTH_SHORT).show();
            }

        }
    }



    @Override
    public void onClick(View v) {
        if (v == ZHUCEJIEMIAN) {
            Intent serverIntent = new Intent(this, RegisterActivity.class); // 跳转登录界面
            startActivity(serverIntent);
        } else if (v == Forgerpassord) {
            Intent serverIntent = new Intent(this, ForgetPassword_activity.class); // 跳转密码重置界面
            startActivity(serverIntent);
        } else {




            if(!CheckPara()){//先检查参数
                return;
            }
            String user = phones.getText().toString();//用户名或者电话号码
            String passward = passwards.getText().toString();//密码
            XqNetClient netClient =  new XqNetClient();
            final JSONObject jsonobject = new JSONObject();
            try {
                jsonobject.put("loginName",user);//用户名或者电话号码
                if(lgswitch.isChecked()){//当前属于验证码登录
                    jsonobject.put("vCode",authcode.getText().toString());
                }else{//当前属于密码登录
                    jsonobject.put("password", MD5Util.md5(passward));//密码
                }
                jsonobject.put("type", lgswitch.isChecked()?SettingManager.AUTHTYPE+"":SettingManager.PASSTYPE+"");//1是密码登录，2是验证码登录
                jsonobject.put("timestamp", TimeUtil.getLastTime());
            } catch (JSONException e) {
                e.printStackTrace();
            }
            showProgressDialog();
            netClient.Login(jsonobject.toString()).enqueue(new Callback<String>() {
                @Override
                public void onResponse(Call<String> call, Response<String> response) {
                    System.out.println("-===获取的验证码是："+ response.body());
                    Log.e(TAG, "-===获取登录信息：" + response.body());
                    String code     =   "";
                    String token    =   "";
                    String uid      =   "";
                    int isSetpwd = 0;
                    boolean issetting = false;
                    String user1 = phones.getText().toString();//用户名或者电话号码
                    try {
                        JSONObject jsonObject = new JSONObject(response.body());
                        code = jsonObject.getString("message");
                        String dates=jsonObject.getString("data");
                        JSONObject object1 = new JSONObject(dates);
                        token = object1.getString("token");
                        uid = object1.getString("uid");
                        isSetpwd = object1.getInt(Stringkey.isSetPwd);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    if (code.equals("成功")) {//如果成功就跳转到主界面
//
                        userInfo = new UserInfo();
                        userInfo.setLogintype(lgswitch.isChecked()?SettingManager.AUTHTYPE:SettingManager.PASSTYPE);
                        userInfo.setPhonenum(user1);

                        userInfo.setToken(token);
                        userInfo.setUid(uid);
                        userInfo.setIssetPwd(isSetpwd);
                        ACache.getInstance().put(Stringkey.USERInfo,userInfo);


                        SettingManager.getInstance(Login_Activity.this).setPhoneNumber(user1);
                        SettingManager.getInstance(Login_Activity.this).setUid(uid);
                        SettingManager.getInstance(Login_Activity.this).setToken(token);
                        SettingManager.getInstance(Login_Activity.this).setLoginType(lgswitch.isChecked()?SettingManager.AUTHTYPE:SettingManager.PASSTYPE);

                        Toast.makeText(Login_Activity.this, "登陆成功", Toast.LENGTH_SHORT).show();
                        queryUserInfo();
                    } else {
                        showToast(Login_Activity.this, "用户名或密码错误");
                    }
                    hideProgressDialog();
                }

                @Override
                public void onFailure(Call<String> call, Throwable t) {
                    t.printStackTrace();
                    hideProgressDialog();
                }
            });
        }

    }

    /**
     * 查询用户信息
     */
    private void queryUserInfo() {
        XqNetClient netClient = new XqNetClient();
        JSONObject jsonobject = new JSONObject();
        try {
            jsonobject.put("token", userInfo.getToken());
            jsonobject.put("uid", userInfo.getUid());
            jsonobject.put("timestamp", TimeUtil.getSystemCurrentTimeLong()+"");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        netClient.queryUserInfo(jsonobject.toString()).enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                if(response.body() == null){
                    showToast(Login_Activity.this, "用户信息没有设置");
                    return;
                }
                Log.e(TAG, "-===获取查询用户信息：" + response.body());
                String code = "1";
                String names = "xaio";
                String sexs = "女";
                int age  = 0;
                try {
                    JSONObject jsonObject1 = new JSONObject(response.body());
                    code = jsonObject1.getString("message");
                    String datas = jsonObject1.getString("data");
                    JSONObject jsonObject2 = new JSONObject(datas);
                    names = jsonObject2.getString("name");
                    sexs = jsonObject2.getString("gender");
                    age = jsonObject2.getInt("age");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (code.equals("成功")) {//如果成功就
                    userInfo.setNickname(names);
                    userInfo.setSex(Integer.parseInt(sexs));
                    userInfo.setAge(age);
                    ACache.get(Login_Activity.this).put(Stringkey.USERInfo, userInfo);

                }else if(code.equals(Stringkey.UserNotSetting)){
                    userInfo.setSetting(false);
                    ACache.get(Login_Activity.this).put(Stringkey.USERInfo, userInfo);
                }
                jumpMainPage();
            }
            @Override
            public void onFailure(Call<String> call, Throwable t) {
                t.printStackTrace();
            }
        });
    }


    private void  jumpMainPage(){
        //d登录成功，需要设置别名


        Intent serverIntent = new Intent(Login_Activity.this, Home_Activity.class); // 跳转主界面
        startActivity(serverIntent);
        finish();
    }

    private boolean CheckPara() {
        if(TextUtils.isEmpty(phones.getText())){
            showToast(this, "请输入手机号");
            return  false;
        }

        if(!lgswitch.isChecked() && TextUtils.isEmpty(passwards.getText())){
            showToast(this, "请输至少6位密码");
            return false;
        }

        if(lgswitch.isChecked() && TextUtils.isEmpty(authcode.getText())){
            showToast(this, "请输入验证码");
            return false;
        }

        return true;
    }



    private TextWatcher textWatcher = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {
//
            System.out.println("-1-onTextChanged-->"
                    + phones.getText().toString() + "<--");
            System.out.println("-1-onTextChanged-->"
                    + passwards.getText().toString() + "<--");
            System.out.println("-1-onTextChanged-->"
                    + authcode.getText().toString() + "<--");
            if(!lgswitch.isChecked()){
                if(phones.getText().length()>= 11 && (passwards.getText().length()>=6)){
                    loginbtn.setEnabled(true);
                }else{
                    loginbtn.setEnabled(false);
                }
            }else{
                if(phones.getText().length()>= 11 && (authcode.getText().length() == 6)){
                    loginbtn.setEnabled(true);
                }else{
                    loginbtn.setEnabled(false);
                }
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//
        }

        @Override
        public void afterTextChanged(Editable s) {
//
        }
    };

}
